package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.cj.util.StringUtils;

import bean.UserBean;
import jdbc.DBUtils;

public class UserDao {
	public UserBean findUsername(String username){
		Connection con =null;
		PreparedStatement pstmt =null;
		ResultSet rs = null;
		UserBean userBean= null;
		try {
			con = DBUtils.getConnection();
			String sql = "select * from user where userId=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, username);
			rs = pstmt.executeQuery();
			if(rs==null){
				return null;
			}
			if(rs.next()){
				String psw=rs.getString("password");
				String userId=rs.getString("userId");
				if (!StringUtils.isNullOrEmpty(userId) && !StringUtils.isNullOrEmpty(psw) ) {
					userBean = new UserBean();
					userBean.setUserId(userId);
					userBean.setPassword(psw);
				}
			}
		}  catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtils.close(pstmt, con);
		}
		return userBean;
	}
	public void insertUser(String username,String psw){
		Connection con =null;
		PreparedStatement pstmt =null;
		try {
			con = DBUtils.getConnection();
			String sql = "INSERT INTO user VALUES(?,?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, psw);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtils.close(pstmt, con);
		}
	}


}
